package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.mq.listener.vo.IotMsgNotifyData;
import com.zzyl.nursing.mq.listener.vo.IotMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import static com.zzyl.common.constant.CacheConstants.IOT_DEVICE_LAST_DATA;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-06
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IDeviceDataService deviceDataService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 批量保存设备上报数据
     * @param iotMsgNotifyData
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        // 从上报数据中获取设备id,根据设备id判断设备是否存在
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(queryWrapper);
        if (device == null) {
            // 记录设备日志，方便后期维护
            log.warn("设备不存在");
            return;
        }

        // 解析上报数据，循环嵌套，先循环service,再循环物模型，解析设备数据
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        if (CollUtil.isEmpty(services)) {
            log.warn("设备上报数据为空");
            return;
        }

        // 遍历service
        List<DeviceData> deviceDataList = new ArrayList<>();
        services.forEach(service -> {

            // 获取上报时间，并转换上报时间时区
            LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            // 获取上报数据
            Map<String, Object> properties = service.getProperties();
            // 遍历map
            properties.forEach((k, v) -> {
                // 将Map中得每一条数据封装到DeviceData中
                // 将设备中相关信息保存到设备数据中
                DeviceData deviceData = BeanUtil.toBean(device , DeviceData.class);
                // 将id设置为空，解决上一步操作设置id属性值
                deviceData.setId(null);
                deviceData.setFunctionId(k);
                deviceData.setDataValue(v.toString());
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setAlarmTime(alarmTime);
                // 将循环到得每一条数据保存到集合中
                deviceDataList.add(deviceData);
            });
        });

        // 将循环到得集合中的上报数据进行批量保存
        saveBatch(deviceDataList);

        // 同时将最新上报的数据存储到redis中
        // 数据结构采用hash结构
        redisTemplate.opsForHash().put(IOT_DEVICE_LAST_DATA, iotId, JSONUtil.toJsonStr(deviceDataList));


    }

    /**
     * 定时删除设备数据
     */
    @Override
    public void deleteOnTime() {
        // 删除数据库中15天前的数据
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(DeviceData::getAlarmTime, DateUtils.getDateBefore(15));
        deviceDataService.remove(queryWrapper);
    }
}
